<?php
//=====================================================
// 來自於:神奇傑利網 http://www.jerry.com.tw
//=====================================================

class CCharset {

	var $gb_map = "/modules/gb.map"; //請寫上完整的實體檔案路徑位置，而不要使用相對位置
	var $big5_map = "/modules/big5.map"; //請寫上完整的實體檔案路徑位置，例如 /home/test/big.map
	var $dep_char = 127;

	//-----------------------------------------------------------------
	function cbig5_gb($str,$fd) {
		$c=ord(substr($str,0,1));
		$x=ord(substr($str,1,1));
		$address=(($c-160)*510)+($x-1)*2;
		fseek($fd, $address);
		$hi=fgetc($fd);
		$lo=fgetc($fd);
		if($hi == "\0")return "";
		return "$hi$lo";
	}

	function cgb_big5($str,$fd) {
		$c=ord(substr($str,0,1));
		$x=ord(substr($str,1,1));
		$address=(($c-160)*510)+($x-1)*2;
		fseek($fd, $address);
		$hi=fgetc($fd);
		$lo=fgetc($fd);
		if($hi == "\0")return "";
		return "$hi$lo";
	}

	//-----------------------------------------------------------------
	function Big5_Gb($str) {
		$fd = fopen($_SERVER["DOCUMENT_ROOT"].$this -> gb_map, "r");
		//$str=str_replace("charset=BIG5","charset=gb2312", $str);
		//$str=str_replace("charset=big5","charset=gb2312", $str);
		$outstr = "";
		for($i = 0; $i < strlen($str); $i++) {
			$ch = ord(substr($str, $i, 1));
			if($ch > $this -> dep_char) {
				$outstr .= $this -> cbig5_gb(substr($str, $i, 2), $fd);
				$i++;
			} else {
				$outstr .= substr($str, $i, 1);
			}
		}
		fclose($fd);
		return $outstr;
	}

	//-----------------------------------------------------------------

	function Gb_Big5($str) {
		$fd = fopen($_SERVER["DOCUMENT_ROOT"].$this -> big5_map, "r");
		//$str=str_replace("charset=gb2312","charset=big5", $str);
		$outstr = "";
		$strTmp = "";
		for($i = 0; $i < strlen($str); $i++) {
			$ch=ord(substr($str, $i, 1));
			if($ch > $this -> dep_char) {
				$strTmp = $this -> cgb_big5(substr($str, $i, 2), $fd);
				print strlen($strTmp)." = ".$strTmp." = ".addslashes($strTmp)." \n";
				$outstr .= $strTmp;
				$i++;
			} else {
				$outstr .= substr($str, $i, 1);
			}
		}
		fclose($fd);
		return $outstr;
	}
}
?>